
#include "beep.h"

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h> 


//蜂鸣器的初始化
int beep_init(void)
{
	int fd;
	
	//1.申请GPIO

	//打开GPIO导出文件（用于申请GPIO控制权）
	fd = open("/sys/class/gpio/export", O_WRONLY);
	if (fd == -1) 
	{
		perror("open /sys/class/gpio/export error");
		return -1;
	}	
	//写入"111"表示要操作GPIO 111引脚
	write(fd, "111", 3);
	fsync(fd);	// 同步文件状态，确保数据写入硬件
	close(fd);
	
	//2. BUZZ蜂鸣器 设置GPIO方向

	//打开GPIO方向控制文件
	fd = open("/sys/class/gpio/gpio111/direction", O_WRONLY);
	if (fd == -1) 
	{
		perror("open /sys/class/gpio/gpio111/direction error");
		return -1;
	}
	//设置为输出模式("out")，因为蜂鸣器只需要接收信号而不需要读取状态
	write(fd, "out", 3);
	
	fsync(fd);
	close(fd);
}

//led灯的初始化
int led_init(void)
{
	int fd;
	
	/* 申请GPIO */
	fd = open("/sys/class/gpio/export", O_WRONLY);	//打开GPIO导出文件（用于申请GPIO控制权）
	if (fd == -1) 
	{
		perror("open /sys/class/gpio/export error");
		return -1;
	}	
	write(fd, "120", 3);	//写入"120"表示要操作GPIO 120引脚
	write(fd, "121", 3);
	write(fd, "123", 3);
	write(fd, "124", 3);
	fsync(fd);	 // 同步文件状态，确保数据写入硬件
	close(fd);
	
	/* LED1 */
	fd = open("/sys/class/gpio/gpio120/direction", O_WRONLY);
	if (fd == -1) 
	{
		perror("open /sys/class/gpio/gpio120/direction error");
		return -1;
	}	
	write(fd, "out", 3);
	fsync(fd);
	close(fd);
	
	/* LED2 */
	fd = open("/sys/class/gpio/gpio121/direction", O_WRONLY);
	if (fd == -1) 
	{
		perror("open /sys/class/gpio/gpio121/direction error");
		return -1;
	}	
	write(fd, "out", 3);
	fsync(fd);
	close(fd);
	
	/* LED3 */
	fd = open("/sys/class/gpio/gpio123/direction", O_WRONLY);
	if (fd == -1) 
	{
		perror("open /sys/class/gpio/gpio123/direction error");
		return -1;
	}	
	write(fd, "out", 3);
	fsync(fd);
	close(fd);

	/* LED4 */
	fd = open("/sys/class/gpio/gpio124/direction", O_WRONLY);
	if (fd == -1) 
	{
		perror("open /sys/class/gpio/gpio124/direction error");
		return -1;
	}	
	write(fd, "out", 3);
	fsync(fd);
	close(fd);
}


//蜂鸣器和led灯的控制函数
int beep_LED_ctrl( char * ID, int enable )
{
	//1.打开蜂鸣器或led灯 文件
	int fd = open( ID, O_WRONLY);
	if (fd == -1) 
	{
		perror("open beep/led error");
		return -1;
	}

	//2.写入指令 --> 控制 
	if( enable == 1 )
	{
		write(fd, "1", 1);
	}
	else 
	{
		write(fd, "0", 1);
	}
	
	//3.关闭文件 
	fsync(fd);	// 同步文件状态，确保数据写入硬件
	close(fd);
}



